﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EasySite.Models;
using EasySite.Services;
using EasySite.Web.Security;
using EasySite.Web.ViewModels.Page;

namespace EasySite.Web.Controllers
{
    public class PageController : ControllerBase
    {
        [Authorize(Roles = Roles.Admin)]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = Roles.Admin)]
        public ActionResult Create()
        {
            return RedirectToAction("Edit");
        }

        [Authorize(Roles = Roles.Admin)]
        public ActionResult Edit(int? id)
        {
            var viewModel = new EditViewModel();
            viewModel.Page = new Page();
            return View(viewModel);
        }

        [Authorize(Roles = Roles.Admin)]
        [ValidateInput(false)]
        [HttpPost]
        public JsonResult Save(Page page)
        {
            var result = new CustomResult<int>();
            var service = base.GetService<IPageService>();
            if (page.ID == 0)
            {
                result.Success = service.CreatePage(page);
            }
            else
            {
                result.Success = service.UpdatePage(page);
            }
            result.Value = page.ID;
            return Json(result);
        }

        public ActionResult Render()
        {
            var page = new Page();
            page.Title = DateTime.Now.ToString();
            page.Content = Request.RawUrl;
            return View(page);
        }
    }
}
